<template>
  <div class="remote-control">
    <!-- 全屏容器 -->
    <div class="fullscreen-container" ref="fullscreenContainer">
      <!-- 屏幕显示区域 -->
      <div class="screen-display" ref="screenDisplay">
        <img
          v-if="screenData"
          :src="screenData"
          alt="远程屏幕"
          class="screen-image"
          @click="handleScreenClick"
          @mousemove="handleMouseMove"
          @contextmenu.prevent="handleRightClick"
        />

        <div v-else class="screen-placeholder">
          <el-icon class="placeholder-icon"><Monitor /></el-icon>
          <div class="placeholder-text">
            {{ connectionStatus === 'connected' ? '等待屏幕数据...' : '连接中...' }}
          </div>
          <el-progress
            v-if="connectionStatus === 'connecting'"
            :percentage="connectionProgress"
            :show-text="false"
            style="width: 200px; margin-top: 20px;"
          />
        </div>
      </div>

      <!-- 控制面板 -->
      <div class="control-panel" :class="{ 'hidden': controlsHidden }">
        <div class="panel-header">
          <div class="client-info">
            <el-icon><Monitor /></el-icon>
            <span class="client-name">{{ clientInfo.name || clientId }}</span>
            <el-tag
              :type="connectionStatus === 'connected' ? 'success' : 'danger'"
              size="small"
            >
              {{ connectionStatusText }}
            </el-tag>
          </div>

          <div class="panel-actions">
            <el-button
              size="small"
              @click="toggleFullscreen"
              :icon="isFullscreen ? 'FullScreen' : 'Aim'"
            >
              {{ isFullscreen ? '退出全屏' : '全屏' }}
            </el-button>

            <el-button
              size="small"
              @click="toggleStats"
              :type="showStats ? 'primary' : 'default'"
            >
              <el-icon><DataAnalysis /></el-icon>
              统计
            </el-button>

            <el-button size="small" @click="refreshScreen">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>

            <el-button size="small" @click="closeControl" type="danger">
              <el-icon><Close /></el-icon>
              关闭
            </el-button>
          </div>
        </div>

        <!-- 工具栏 -->
        <div class="toolbar">
          <el-button-group>
            <el-button
              size="small"
              :type="controlMode === 'view' ? 'primary' : 'default'"
              @click="setControlMode('view')"
            >
              <el-icon><View /></el-icon>
              查看
            </el-button>

            <el-button
              size="small"
              :type="controlMode === 'control' ? 'primary' : 'default'"
              @click="setControlMode('control')"
            >
              <el-icon><Mouse /></el-icon>
              控制
            </el-button>
          </el-button-group>

          <el-divider direction="vertical" />

          <el-button-group>
            <el-button size="small" @click="sendKeyCommand('ctrl+c')">
              <el-icon><DocumentCopy /></el-icon>
              复制
            </el-button>

            <el-button size="small" @click="sendKeyCommand('ctrl+v')">
              <el-icon><DocumentCopy /></el-icon>
              粘贴
            </el-button>

            <el-button size="small" @click="sendKeyCommand('ctrl+alt+del')">
              <el-icon><Key /></el-icon>
              Ctrl+Alt+Del
            </el-button>
          </el-button-group>

          <el-divider direction="vertical" />

          <div class="quality-control">
            <span class="control-label">画质:</span>
            <el-select v-model="quality" size="small" style="width: 80px;" @change="changeQuality">
              <el-option label="高" value="high" />
              <el-option label="中" value="medium" />
              <el-option label="低" value="low" />
            </el-select>
          </div>
        </div>
      </div>

      <!-- 统计面板 -->
      <div v-if="showStats" class="stats-panel">
        <div class="stats-header">
          <span class="stats-title">实时统计</span>
          <el-button size="small" text @click="showStats = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>

        <div class="stats-content">
          <div class="stat-row">
            <span class="stat-label">客户端:</span>
            <span class="stat-value">{{ clientId }}</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">分辨率:</span>
            <span class="stat-value">{{ clientStats.resolution || '未知' }}</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">帧率:</span>
            <span class="stat-value fps">{{ clientStats.fps || 0 }} FPS</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">延迟:</span>
            <span class="stat-value" :class="latencyClass">{{ clientStats.latency || 0 }} ms</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">数据量:</span>
            <span class="stat-value">{{ clientStats.dataRate || 0 }} KB/s</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">连接时间:</span>
            <span class="stat-value">{{ formatUptime(connectionUptime) }}</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">画质:</span>
            <span class="stat-value">{{ qualityText }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWebSocketStore } from '@/stores/websocket'
import { useClientsStore } from '@/stores/clients'
import {
  Monitor, DataAnalysis, Refresh, Close, View, Mouse,
  DocumentCopy, Key, FullScreen, Aim
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const wsStore = useWebSocketStore()
const clientsStore = useClientsStore()

// 响应式数据
const fullscreenContainer = ref()
const screenDisplay = ref()
const clientId = route.params.clientId
const screenData = ref(null)
const controlsHidden = ref(false)
const showStats = ref(false)
const isFullscreen = ref(false)
const controlMode = ref('view') // 'view' | 'control'
const quality = ref('high')
const connectionProgress = ref(0)
const connectionUptime = ref(0)
const directConnection = ref(null)
const directConnectionStatus = ref('disconnected') // 'connected' | 'connecting' | 'disconnected'

// 计算属性
const connectionStatus = computed(() => {
  // 如果有直连，使用直连状态，否则使用WebSocket store状态
  return directConnection.value ? directConnectionStatus.value : wsStore.connectionStatus
})

const connectionStatusText = computed(() => {
  const statusMap = {
    connected: '已连接',
    connecting: '连接中',
    disconnected: '已断开'
  }
  return statusMap[connectionStatus.value] || '未知'
})

const clientInfo = computed(() => {
  return clientsStore.getClient(clientId) || {}
})

const clientStats = computed(() => {
  return wsStore.stats.get(clientId) || {}
})

const latencyClass = computed(() => {
  const latency = clientStats.value.latency || 0
  if (latency < 50) return 'latency-low'
  if (latency < 150) return 'latency-medium'
  return 'latency-high'
})

const qualityText = computed(() => {
  const qualityMap = {
    high: '高清',
    medium: '标清',
    low: '流畅'
  }
  return qualityMap[quality.value] || '未知'
})

// 方法
const handleScreenClick = (event) => {
  if (controlMode.value !== 'control') return

  const rect = event.target.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  sendMouseCommand('click', { x, y })
}

const handleMouseMove = (event) => {
  if (controlMode.value !== 'control') return

  const rect = event.target.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  // 节流处理，避免发送过多消息
  throttle(() => {
    sendMouseCommand('move', { x, y })
  }, 50)
}

const handleRightClick = (event) => {
  if (controlMode.value !== 'control') return

  const rect = event.target.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  sendMouseCommand('rightclick', { x, y })
}

const sendMouseCommand = (action, position) => {
  wsStore.sendControlCommand(clientId, {
    action: 'mouse',
    type: action,
    x: position.x,
    y: position.y
  })
}

const sendKeyCommand = (keys) => {
  wsStore.sendControlCommand(clientId, {
    action: 'keyboard',
    keys: keys
  })
  ElMessage.success(`已发送快捷键: ${keys}`)
}

const setControlMode = (mode) => {
  controlMode.value = mode
  ElMessage.info(`切换到${mode === 'view' ? '查看' : '控制'}模式`)
}

const changeQuality = (newQuality) => {
  wsStore.sendControlCommand(clientId, {
    action: 'change_quality',
    quality: newQuality
  })
  ElMessage.success(`画质已切换到${qualityText.value}`)
}

const toggleFullscreen = async () => {
  if (!document.fullscreenElement) {
    await fullscreenContainer.value.requestFullscreen()
    isFullscreen.value = true
  } else {
    await document.exitFullscreen()
    isFullscreen.value = false
  }
}

const toggleStats = () => {
  showStats.value = !showStats.value
}

const refreshScreen = () => {
  wsStore.sendControlCommand(clientId, {
    action: 'refresh_screen'
  })
  ElMessage.success('已刷新屏幕')
}

const closeControl = () => {
  if (window.opener) {
    window.close()
  } else {
    router.push('/dashboard')
  }
}

const formatUptime = (seconds) => {
  if (!seconds) return '00:00:00'

  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 节流函数
const throttle = (func, delay) => {
  let timeoutId
  let lastExecTime = 0

  return function (...args) {
    const currentTime = Date.now()

    if (currentTime - lastExecTime > delay) {
      func.apply(this, args)
      lastExecTime = currentTime
    } else {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(() => {
        func.apply(this, args)
        lastExecTime = Date.now()
      }, delay - (currentTime - lastExecTime))
    }
  }
}

// 键盘事件处理
const handleKeyDown = (event) => {
  if (controlMode.value !== 'control') return

  // 阻止默认行为
  event.preventDefault()

  // 构建按键组合
  const keys = []
  if (event.ctrlKey) keys.push('ctrl')
  if (event.altKey) keys.push('alt')
  if (event.shiftKey) keys.push('shift')
  keys.push(event.key.toLowerCase())

  sendKeyCommand(keys.join('+'))
}

// 自动隐藏控制面板
let hideControlsTimer
const resetHideControlsTimer = () => {
  clearTimeout(hideControlsTimer)
  controlsHidden.value = false

  hideControlsTimer = setTimeout(() => {
    if (isFullscreen.value) {
      controlsHidden.value = true
    }
  }, 3000)
}

// 生命周期
onMounted(() => {
  // 启动屏幕共享
  wsStore.sendControlCommand(clientId, {
    action: 'start_screen_sharing'
  })

  // 监听全屏变化
  document.addEventListener('fullscreenchange', () => {
    isFullscreen.value = !!document.fullscreenElement
  })

  // 监听键盘事件
  document.addEventListener('keydown', handleKeyDown)

  // 监听鼠标移动（用于显示控制面板）
  document.addEventListener('mousemove', resetHideControlsTimer)

  // 启动连接时间计时器
  const uptimeTimer = setInterval(() => {
    if (connectionStatus.value === 'connected') {
      connectionUptime.value++
    }
  }, 1000)

  // 模拟连接进度
  const progressTimer = setInterval(() => {
    if (connectionStatus.value === 'connecting' && connectionProgress.value < 100) {
      connectionProgress.value += 10
    } else {
      clearInterval(progressTimer)
    }
  }, 200)

  onUnmounted(() => {
    clearInterval(uptimeTimer)
    clearInterval(progressTimer)
    clearTimeout(hideControlsTimer)
    document.removeEventListener('keydown', handleKeyDown)
    document.removeEventListener('mousemove', resetHideControlsTimer)

    // 停止屏幕共享
    wsStore.sendControlCommand(clientId, {
      action: 'stop_screen_sharing'
    })
  })
})
</script>

<style scoped>
.remote-control {
  height: 100vh;
  background: #000;
  overflow: hidden;
}

.fullscreen-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.screen-display {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
  overflow: hidden;
}

.screen-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  cursor: crosshair;
}

.screen-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  text-align: center;
}

.placeholder-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.6;
}

.placeholder-text {
  font-size: 18px;
  margin-bottom: 20px;
}

.control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.9);
  border-radius: 12px;
  padding: 15px;
  color: white;
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
  z-index: 1000;
  min-width: 400px;
}

.control-panel.hidden {
  opacity: 0;
  pointer-events: none;
  transform: translateY(-10px);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.client-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.client-name {
  font-weight: 600;
  font-size: 16px;
}

.panel-actions {
  display: flex;
  gap: 8px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.control-label {
  font-size: 14px;
  color: #ccc;
}

.quality-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-panel {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.9);
  border-radius: 12px;
  padding: 15px;
  color: white;
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  min-width: 250px;
  z-index: 1000;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.stats-title {
  font-weight: 600;
  font-size: 14px;
}

.stats-content {
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.stat-row:last-child {
  margin-bottom: 0;
}

.stat-label {
  color: #ccc;
}

.stat-value {
  font-weight: bold;
}

.stat-value.fps {
  color: #409EFF;
}

.stat-value.latency-low {
  color: #67C23A;
}

.stat-value.latency-medium {
  color: #E6A23C;
}

.stat-value.latency-high {
  color: #F56C6C;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .control-panel {
    min-width: 300px;
    top: 10px;
    right: 10px;
    padding: 10px;
  }

  .toolbar {
    flex-direction: column;
    gap: 10px;
  }

  .stats-panel {
    bottom: 10px;
    left: 10px;
    min-width: 200px;
  }
}
</style>
